﻿using Kaskelot.SP.Core;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Publishing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;

namespace Kaskelot.SP.Services.Setup
{
	public abstract class RootSetup
	{
		public static void Setup(string rootUrl)
		{
			using (SPSite site = new SPSite(rootUrl))
			{
				using (SPWeb web = site.OpenWeb())
				{
					// Create startpage
					web.Features.Reactivate(Constants.Features.StartPage);

					#region Sub sites
					// Byggnad
					EnsureSubWeb(web, Constants.Byggnad.WebName, new ByggnadWebSetup());

					// Person
					EnsureSubWeb(web, Constants.Person.WebName, new PersonWebSetup());

					// Admin
					EnsureSubWeb(web, Constants.Admin.WebName, new AdminWebSetup());

					// Bemanning
					EnsureSubWeb(web, Constants.Bemanning.WebName, new BemanningWebSetup());

					// Kurser
					EnsureSubWeb(web, Constants.Kurser.WebName, new KursWebSetup());

					// Analys
					EnsureSubWeb(web, Constants.Analys.WebName, new AnalysWebSetup());
					#endregion

					web.Features.Reactivate(Constants.Features.Groups);

					var v = PublishingWeb.GetPublishingWeb(web);
					v.Navigation.GlobalIncludePages = false;
					v.Update();

					//var cs = SPWebService.ContentService;
					//cs.ClientRequestServiceSettings.MaxReceivedMessageSize = -1;
					//var settings = new SPWcfServiceSettings();
					//settings.MaxBufferSize = Int32.MaxValue;
					//settings.MaxReceivedMessageSize = Int32.MaxValue;
					//settings.ReaderQuotasMaxArrayLength = Int32.MaxValue;
					//settings.ReaderQuotasMaxBytesPerRead = Int32.MaxValue;
					//settings.ReaderQuotasMaxDepth = 64;
					//settings.TransferMode = TransferMode.Buffered;
					//cs.WcfServiceSettings["clientpersonservice.svc"] = settings;
					//cs.Update();
				}
			}
		}

		private static void EnsureSubWeb(SPWeb parentWeb, string name, IWebSetup setup)
		{
            SPWeb subWeb = parentWeb.Webs[name];
            try
            {                
                if (!subWeb.Exists)
                {
                    SPWebTemplate subWebTemplate = parentWeb.GetAvailableWebTemplates(parentWeb.Language)[Constants.WebTemplates.MainSubWebTemplate];
                    subWeb = parentWeb.Webs.Add(name, name, string.Empty, parentWeb.Language, subWebTemplate, false, false);
                }
                setup.Setup(subWeb);
            }
            finally
            {
                subWeb.Dispose();
            }            
		}
	}
}
